package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.ResultBean;
import entity.UserBean;

@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String REG_SUCCESS = "login.jsp";
	private static final String PHONE_REG_SUCCESS = "phone-login.jsp";
	private static final String FALT = "register.jsp";
	private static final String PHONE_FALT = "phone-register.jsp";
       
    public Register() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String callback = request.getParameter("callback");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		String url = "";
		UserBean user = new UserBean(username,password);
		ResultBean<?> result = user.checkUsername(username);
		if(result.getCode() == ResultBean.SUCCESS){
			result = user.save();
		}
		if(result.getCode() == ResultBean.REG_SUCCESS){
			if(phone.equals("true")){
				url = PHONE_REG_SUCCESS;
			}else{
				url = REG_SUCCESS;
			}
		}else{
			if(phone.equals("true")){
				url = PHONE_FALT;
			}else{
				url = FALT;
			}
		}
		request.setAttribute("result", result);
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
